package com.daervin.svc.parser.hot;

import com.daervin.svc.common.constants.Constants;
import com.daervin.svc.common.constants.HotSiteEnum;
import com.daervin.svc.common.dto.hot.ZhiHuHotData;
import com.daervin.svc.common.dto.hot.ZhiHuHotResult;
import com.daervin.svc.common.utils.NumberUtil;
import com.daervin.svc.dal.model.HotItem;
import com.daervin.svc.parser.RootParser;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Json;

import java.util.ArrayList;
import java.util.List;

import static com.daervin.svc.common.constants.HotSiteEnum.*;

/**
 * @author daervin
 * @version 1.0.0
 * @since 1.0.0
 */
public class ZhiHuHotParser extends RootParser {

    private final static Logger LOGGER = Logger.getLogger(ZhiHuHotParser.class);

    public ZhiHuHotParser(String[] url) {
        super(url);
    }

    @Override
    public void listProcess(Page page) {
        Json responseJson = page.getJson();
        if (responseJson == null) {
            return;
        }
        ZhiHuHotResult response = responseJson.toObject(ZhiHuHotResult.class);
        if (response == null || CollectionUtils.isEmpty(response.getData())) {
            return;
        }
        String url = page.getUrl().get();
        HotSiteEnum hotSiteEnum = null;
        if(ZHIHU_HOT.TOPIC_URL.equalsIgnoreCase(url)){
            hotSiteEnum =ZHIHU_HOT;
        }
        if(ZHIHU_SPORT.TOPIC_URL.equalsIgnoreCase(url)){
            hotSiteEnum =ZHIHU_SPORT;
        }
        if(ZHIHU_CAR.TOPIC_URL.equalsIgnoreCase(url)){
            hotSiteEnum =ZHIHU_CAR;
        }

        List<HotItem> hotItemList = new ArrayList<>();
        for (ZhiHuHotData data : response.getData()) {
            if (StringUtils.isEmpty(data.getDetailText()) || data.getTarget() == null) {
                continue;
            }
            String scoreStr = data.getDetailText().replaceAll("热度","").replaceAll("领域","").replaceAll("万","");
            Long score = NumberUtil.safeParseNumber(scoreStr, Long.class);
            String link = "https://www.zhihu.com/question/" + data.getTarget().getId();
            String title = data.getTarget().getTitle();
            hotItemList.add(new HotItem(hotSiteEnum.ID, title, link, score * 10000));
        }
        if (CollectionUtils.isEmpty(hotItemList)) {
            return;
        }
        page.putField(Constants.PARSER_RESULT, hotItemList);
    }
}
